import sys

from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcsms.v1.region.csms_region import CsmsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcsms.v1 import *
import csv
import re

configKey = 'configKey'
configValue = 'configValue'
configFileName = 'configFileName'

def writeSecret(regionId,ak,sk,enterpriseProjectId,name,secret):
    credentials = BasicCredentials(ak, sk)
    client = CsmsClient.new_builder().with_credentials(credentials).with_region(CsmsRegion.value_of(regionId)).build()

    try:
        request = CreateSecretRequest()
        request.body = CreateSecretRequestBody(
            enterprise_project_id=enterpriseProjectId,
            secret_string=secret,
            name=name
        )
        response = client.create_secret(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

def specialCharacters(value):
    pattern = r'[\[\]!@#$%^&*()<>?/\|{}~:]'
    if re.search(pattern, value):
        return True
    else:
        return False

def readConfig(filePath):
    configs = []
    file = open(filePath,'r')
    csvReader = csv.reader(file)
    try:
        count = 0;
        for row in csvReader:
            count = count + 1
            if count == 1:
                continue
            if len(row) == 0:
                continue
            if len(row) < 2:
                print('Incorrect config: please modify it')
                print(row)
                exit(-9)
            if specialCharacters(row[0]):
                print('There are special characters present: please modify it')
                print(row)
                exit(-9)
            configDict = {configFileName: row[0], configValue: row[1]}
            configs.append(configDict)

    finally:
        file.close()
    return configs



if __name__ == '__main__':
    if(len(sys.argv) < 6):
        print('Incorrect parameter input\n')
        print('The correct parameters are:regionId,Access Key Id,Secret Access Key,enterprise project id,configuration file path \n')
        print('Please try it again \n')
        exit(-9)
    regionId = sys.argv[1]
    ak = sys.argv[2]
    sk = sys.argv[3]
    enterpriseProjectId = sys.argv[4]
    configurationFilePath = sys.argv[5]
    print('%s,%s,%s,%s',ak,sk,enterpriseProjectId,configurationFilePath)
    configs = readConfig(configurationFilePath)
    for configDict in configs:
        writeSecret(ak,sk,enterpriseProjectId,configDict[configFileName],configDict[configValue])
    print("Success write secrets, total num is : " + str(len(configs)))

